package example.hello_security.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtil {

    @Autowired
    JwtEncoder jwtEncoder;

    @Autowired
    JwtDecoder jwtDecoder;

    /**
     * @description 获取claim部分
     * @author zken
     * @CreateDate 2024/10/26 23:18:52
     */
    public Map<String, Object> getDecodedToken(String token) {
        return jwtDecoder.decode(token).getClaims();
    }

    public String createToken(Map<String, Object> claimsMap, long ttlInSeconds, ChronoUnit unit) {

        // 插嘴知识
        /*
        Map.Entry 是规范的访问map的方法，如果你需要访问map，请这么操作
               for (Map.Entry<String, Object> entry : claimsMap.entrySet()) {
                        c.put(entry.getKey(), entry.getValue());
                    }

         */

        JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
                .claims(c -> {
                    c.putAll(claimsMap);
                })
                .expiresAt(Instant.now().plus(ttlInSeconds,unit)) // 设置过期时间
                .build();

        JwtEncoderParameters jwtEncoderParameters = JwtEncoderParameters.from(jwtClaimsSet);

        Jwt jwt = jwtEncoder.encode(jwtEncoderParameters);
        return jwt.getTokenValue();
    }


}
